package com.chaofan.quick_search;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;

/**
 * Created by Chaofan at 2018/8/22 16:22
 * email:chaofan2685@qq.com
 **/
@RestController
public class CopyController {

    private static final Logger logger = LoggerFactory.getLogger(CopyController.class);

    @RequestMapping(value = "/")
    public void copy(){
        try {
            Robot robot = new Robot();
            //模拟三大快捷键的抬起事件，以防止按键冲突
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.keyRelease(KeyEvent.VK_SHIFT);
            robot.keyRelease(KeyEvent.VK_ALT);
            robot.delay(100);//必不可少

            //模拟Alt+Tab,切换回上一个的窗口，也就是有选中文字的窗口
            robot.keyPress(KeyEvent.VK_ALT);
            robot.keyPress(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_ALT);
            robot.delay(100);//必不可少

            //模拟Ctrl+C，复制文字
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_C);
            robot.keyRelease(KeyEvent.VK_C);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(100);//必不可少

            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            //从系统剪切板中获取数据
            Transferable content = clipboard.getContents(null);
            //判断是否为文本类型
            if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                //从数据中获取文本值
                String text = (String) content.getTransferData(DataFlavor.stringFlavor);
                if (text == null) {
                    return;
                }
                //拼接一条命令
                String url = "rundll32 url.dll,FileProtocolHandler https://www.baidu.com/s?wd=";
                //执行命令
                Runtime.getRuntime().exec(url+text);
            }
            //清空剪切板（可有可无）
//            Transferable tText = new StringSelection("");
//            clipboard.setContents(tText,null);
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作失败！");
        }
    }

}
